package com.training.bt.service;

import java.time.LocalDateTime;
import java.util.List;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.training.bt.common.PageResponseDTO;
import com.training.bt.entity.PointsRecord;
import com.training.bt.entity.User;
import com.training.bt.enums.PointsChangeType;
import com.training.bt.mapper.PointsRecordMapper;
import com.training.bt.security.util.SecurityUtils;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class PointsRecordService {
    private final PointsRecordMapper pointsRecordMapper;

    public void pointsAdd(Long userId, int points) {
        PointsRecord pointsRecord = new PointsRecord();
        pointsRecord.setUserId(userId);
        pointsRecord.setChangeType(PointsChangeType.RECHARGE);
        pointsRecord.setChangeNum(points);
        pointsRecord.setRecordTime(LocalDateTime.now());

        pointsRecordMapper.insert(pointsRecord);
    }

    public void pointConsume(Long userId, int points) {
        PointsRecord pointsRecord = new PointsRecord();
        pointsRecord.setUserId(userId);
        pointsRecord.setChangeType(PointsChangeType.CONSUME);
        pointsRecord.setChangeNum(points);
        pointsRecord.setRecordTime(LocalDateTime.now());

        pointsRecordMapper.insert(pointsRecord);
    }

    public void PointRecharge(Long userId, int points) {
        PointsRecord pointsRecord = new PointsRecord();
        pointsRecord.setUserId(userId);
        pointsRecord.setChangeType(PointsChangeType.RECHARGE);
        pointsRecord.setChangeNum(points);
        pointsRecord.setRecordTime(LocalDateTime.now());

        pointsRecordMapper.insert(pointsRecord);
    }

    public PageResponseDTO<PointsRecord> getUserList(int page,int size){
        Page<PointsRecord> pageRequest= new Page<>(page, size);
        User user = SecurityUtils.getCurrentUser();

        LambdaQueryWrapper<PointsRecord> wrapper = new LambdaQueryWrapper<PointsRecord>()
            .eq(PointsRecord::getUserId, user.getId());

        Page<PointsRecord> result = pointsRecordMapper.selectPage(pageRequest, wrapper);

        List<PointsRecord> recordsList = result.getRecords();

        return new PageResponseDTO<>(result.getTotal(), recordsList);
    }
}
